package com.gepengjun.lims.controler;

import com.gepengjun.lims.entity.*;
import com.gepengjun.lims.service.*;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {

    protected static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private DefaultKaptcha myKaptcha;

    @Autowired
    private UserService userService;

    @Autowired
    private RefRoleUserService refRoleUserService;

    @Autowired
    private RefPermissionRoleService refPermissionRoleService;

    @Autowired
    private OrgnazationService orgnazationService;

    @Autowired
    private PermissionService permissionService;


    @RequestMapping(value = "/kaptcha", method = RequestMethod.GET)
    @ResponseBody
    public String kaptcha(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException {
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        response.setHeader("Cache-Control", "post-check=0,pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String validateCode = myKaptcha.createText();
        logger.info("新建验证码----"+validateCode);
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, validateCode);
        BufferedImage bufferedImage = myKaptcha.createImage(validateCode);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        try {
            servletOutputStream.flush();
        } finally {
            servletOutputStream.close();

        }
        return null;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request, ModelMap map) {
        String exception = (String) request.getAttribute("shiroLoginFailure");
        logger.info("login-----exception----"+exception);
        if (exception != null) {
            if ("kaptchaValidateFailed".equals(exception)) {
                map.addAttribute("loginError", "验证码错误");

            } else if (AccountException.class.getName().equals(exception) || IncorrectCredentialsException.class.getName().equals(exception)) {
                map.addAttribute("loginError", "账号或密码错误");

            } else if (DisabledAccountException.class.getName().equals(exception)) {
                map.addAttribute("loginError", "账号已被禁用");

            }else if (LockedAccountException.class.getName().equals(exception)) {
                map.addAttribute("loginError", "账号密码输错已达5次,禁止登陆1小时");

            }
            return "/login";
        }
        logger.info("login-----/index----");
        return "/index";
    }


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(HttpServletRequest request) {
        return "login";
    }

    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request, ModelMap map) {
        logger.info("index-----------------------");
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute("user");
        logger.info("index---"+user.getUserId());
        user = userService.selectById(user.getUserId());
        Orgnazation dept = orgnazationService.findDeptByUserId(user.getUserId());
        user.setDept(dept);
        user.setCompany(orgnazationService.selectById(dept.getParentId()));
        map.addAttribute("user",user);

        //顶部导航菜单
        List<Permission> permissionList = permissionService.findTopMenus();
        map.addAttribute("permissionList",permissionList);

        //用户权限
        List<Permission> userPermissionList = permissionService.findByUserId(user.getUserId());
        List<String> permissionStrList = new ArrayList<>();
        for (Permission permission:userPermissionList){
            permissionStrList.add(permission.getPermissionStr());
        }
        request.getSession().setAttribute("permissionStrList",permissionStrList);

        return "index";
    }

    @RequestMapping(value = "/unautho")
    public String unautho() {
        return "unautho";
    }

    @RequestMapping(value = "/kickout")
    public String kickout() {
        return "redirect:/login";
    }

    @RequestMapping(value = "")
    public String toIndex(ModelMap map) {
        return "redirect:/index";
    }

}